
const mysql = require('../db/mysql');
const researcherDao = require('../sql/researcherDao')
const dateUtils = require('../utils/dateUtils')
const { v4: uuidv4 } = require('uuid');
const transection = require('../db/transection')


exports.researcher = async (req, res)=>{
    try {
        let num = (req.query.currentPage-1)*req.query.count||0;
        let count = +req.query.count||3;
        let row = await mysql(researcherDao.limitAll, [num, count]);
        let total = await mysql(researcherDao.total);
        res.success({
            data: row,
            total: total[0].total
        });
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}

exports.researcherById = async (req, res)=>{
    try {
        let row = await mysql(researcherDao.selectById, [req.query.id]);
        res.success(row);
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}



exports.add = async (req, res)=>{
    try {
        req.body.id = uuidv4();
        req.body.date = dateUtils.getNowDate();
        let row = await mysql(researcherDao.insert, [req.body])
        if(row.affectedRows==1) res.success({},'添加成功');
        else res.fail('添加失败')
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}


exports.delete = async (req, res)=>{
    try {
        if(!Array.isArray(req.body)) return res.fail('数据类型错误')
        // 开启事务
        transection([
            {
                sql: researcherDao.delete,
                values: [req.body]
            }
        ]).then(e=>{
            return res.success({},'删除成功');
        }).catch(()=>{
            return res.fail('删除失败')
        })
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}

exports.update = async (req, res)=>{
    try {
        let body = {};
        req.body.name?body.name = req.body.name:null;
        req.body.avatar?body.avatar = req.body.avatar:null;
        req.body.text?body.text = req.body.text:null;
        req.body.job_title?body.job_title = req.body.job_title:null;
        req.body.research_field?body.research_field = req.body.research_field:null;
        let row = await mysql(researcherDao.updateById, [body, req.body.id])
        if(row.affectedRows==1) res.success({},'修改成功');
        else res.fail('修改失败')
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}



